<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { MapLocation, Warning, Check, Close, Camera, ArrowLeft } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import Polyline from '@arcgis/core/geometry/Polyline'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel'
import gaodeLayer from '@/utils/GaoDeBaseLayer'

const router = useRouter()

// 地图和图层
let view: __esri.MapView
let roadDamageLayer: __esri.FeatureLayer
let sketchViewModel: __esri.SketchViewModel
let newRoadLine: Polyline | null = null

// 表单相关
const formRef = ref<FormInstance>()
const showFormDrawer = ref(false)
const isSubmitting = ref(false)
const isAddingMode = ref(false)

// 表单数据
const formData = reactive({
  roadName: '',
  damageType: '',
  severityLevel: '',
  description: '',
  photoBase64: '',
  reportUser: '访客',
  reportTime: '',
  status: '待处理',
  priority: '中',
  remark: '',
})

// 表单验证规则
const rules = reactive<FormRules>({
  roadName: [
    { required: true, message: '请输入道路名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  damageType: [{ required: true, message: '请选择损坏类型', trigger: 'change' }],
  severityLevel: [{ required: true, message: '请选择严重程度', trigger: 'change' }],
  description: [
    { required: true, message: '请输入损坏描述', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' },
  ],
})

// 损坏类型选项
const damageTypeOptions = [
  { value: '路面裂缝', label: '路面裂缝' },
  { value: '路面坑洼', label: '路面坑洼' },
  { value: '路面沉降', label: '路面沉降' },
  { value: '井盖损坏', label: '井盖损坏' },
  { value: '标线模糊', label: '标线模糊' },
  { value: '交通设施损坏', label: '交通设施损坏' },
  { value: '其他', label: '其他' },
]

// 严重程度选项
const severityLevelOptions = [
  { value: '轻微', label: '轻微' },
  { value: '中等', label: '中等' },
  { value: '严重', label: '严重' },
  { value: '危险', label: '危险' },
]

// 初始化地图
const initMap = async () => {
  // 创建地图实例
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
  })

  // 创建地图视图
  view = new MapView({
    container: 'visitorMapView',
    map: map,
    center: [116.3912, 39.9073], // 北京市中心坐标
    zoom: 12,
    popup: {
      dockEnabled: true,
      dockOptions: {
        buttonEnabled: false,
        breakpoint: false,
      },
    },
  })

  // 创建道路损坏要素图层
  roadDamageLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/gcgG56UMRGbwuqfF/arcgis/rest/services/RoadDamageSegment/FeatureServer/0',
    outFields: ['*'],
    popupTemplate: {
      title: '{roadName}',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'damageType', label: '损坏类型' },
            { fieldName: 'severityLevel', label: '严重程度' },
            { fieldName: 'reportTime', label: '报告时间' },
            { fieldName: 'status', label: '处理状态' },
            { fieldName: 'description', label: '描述' },
          ],
        },
      ],
    },
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-line',
        color: [255, 0, 0, 0.8], // 红色
        width: 4,
        style: 'solid',
      },
    },
  })

  // 将图层添加到地图
  map.add(roadDamageLayer)

  // 初始化草图模型
  sketchViewModel = new SketchViewModel({
    view: view,
    layer: view.graphics,
    polylineSymbol: {
      type: "simple-line",
      color: [255, 0, 0, 0.8],
      width: 4
    }
  })

  // 监听草图完成事件
  sketchViewModel.on("create", (event) => {
    if (event.state === "complete") {
      // 获取绘制的线要素
      newRoadLine = event.graphic.geometry as Polyline

      // 打开创建表单
      isAddingMode.value = false
      resetForm()
      showFormDrawer.value = true
    }
  })
}

// 进入添加模式
const enterAddingMode = () => {
  isAddingMode.value = true

  // 清除之前的图形
  view?.graphics.removeAll()

  // 启动线要素绘制
  sketchViewModel.create("polyline")

  ElMessage.info('请在地图上绘制损坏道路的路段')
}

// 取消添加模式
const cancelAddingMode = () => {
  isAddingMode.value = false

  // 取消绘制
  sketchViewModel.cancel()

  // 清除临时标记
  view?.graphics.removeAll()
}



// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }

  // 设置默认值
  formData.reportUser = '访客'
  formData.reportTime = new Date().toLocaleString()
  formData.status = '待处理'
  formData.priority = '中'
  formData.remark = ''
}

// 上传图片
const handleImageUpload = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]

    // 检查文件大小 (限制为 5MB)
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.warning('图片大小不能超过 5MB')
      return
    }

    const reader = new FileReader()
    reader.onload = (e) => {
      if (e.target) {
        formData.photoBase64 = e.target.result as string
      }
    }
    reader.readAsDataURL(file)
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写必填字段')
      return
    }

    if (!newRoadLine) {
      ElMessage.warning('无法获取损坏道路路段')
      return
    }

    try {
      isSubmitting.value = true

      // 准备属性数据
      const attributes = { ...formData }

      // 创建新要素
      const graphic = new Graphic({
        geometry: newRoadLine,
        attributes: attributes,
      })

      // 提交到服务器
      const result = await roadDamageLayer.applyEdits({
        addFeatures: [graphic],
      })

      if (result.addFeatureResults.length > 0) {
        ElMessage.success('道路损坏信息已提交')
        showFormDrawer.value = false
        view?.graphics.removeAll()

        // 显示成功对话框
        ElMessageBox.alert('感谢您的报告！我们将尽快处理您提交的道路损坏信息。', '提交成功', {
          confirmButtonText: '确定',
          type: 'success',
        })
      } else {
        ElMessage.error('提交失败')
      }
    } catch (error) {
      console.error('提交道路损坏信息失败', error)
      ElMessage.error('提交失败，请稍后重试')
    } finally {
      isSubmitting.value = false
    }
  })
}

// 返回欢迎页
const goToWelcome = () => {
  router.push('/welcome')
}

onMounted(() => {
  initMap()
})
</script>

<template>
  <div class="visitor-map-container">
    <div class="visitor-map-header">
      <div class="header-left">
        <el-button @click="goToWelcome" plain>
          <el-icon><arrow-left /></el-icon> 返回首页
        </el-button>
      </div>
      <div class="header-title">
        <h1>道路损坏报告</h1>
        <p>您可以在地图上标记损坏的道路位置并提交报告</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="enterAddingMode">
          <el-icon><Warning /></el-icon> 报告道路损坏
        </el-button>
      </div>
    </div>

    <div class="map-wrapper">
      <div id="visitorMapView" class="map-container"></div>

      <!-- 状态指示器 - 添加模式 -->
      <div class="status-indicator" v-if="isAddingMode">
        <div class="pulse-dot"></div>
        <span>请在地图上绘制损坏道路的路段，点击添加点，双击完成绘制</span>
        <el-button size="small" @click="cancelAddingMode" class="cancel-btn">取消</el-button>
      </div>
    </div>

    <!-- 提交表单抽屉 -->
    <el-drawer
      v-model="showFormDrawer"
      title="报告道路损坏"
      direction="rtl"
      size="400px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        label-position="top"
        class="damage-form"
      >
        <el-form-item label="道路名称" prop="roadName">
          <el-input v-model="formData.roadName" placeholder="请输入道路名称"></el-input>
        </el-form-item>

        <el-form-item label="损坏类型" prop="damageType">
          <el-select v-model="formData.damageType" placeholder="请选择损坏类型" style="width: 100%">
            <el-option
              v-for="item in damageTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="严重程度" prop="severityLevel">
          <el-select
            v-model="formData.severityLevel"
            placeholder="请选择严重程度"
            style="width: 100%"
          >
            <el-option
              v-for="item in severityLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="损坏描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述道路损坏情况"
          ></el-input>
        </el-form-item>

        <el-form-item label="上传照片" class="upload-item">
          <div class="upload-container">
            <input
              type="file"
              accept="image/*"
              id="photoUpload"
              @change="handleImageUpload"
              class="file-input"
            />
            <label for="photoUpload" class="upload-button">
              <el-icon><Camera /></el-icon>
              <span>选择图片</span>
            </label>
            <div class="file-name" v-if="formData.photoBase64">已选择图片</div>
          </div>
          <div class="image-preview" v-if="formData.photoBase64">
            <img :src="formData.photoBase64" alt="预览图" />
          </div>
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button type="primary" @click="submitForm" :loading="isSubmitting">
            <el-icon><Check /></el-icon> 提交报告
          </el-button>
          <el-button @click="showFormDrawer = false">
            <el-icon><Close /></el-icon> 取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<style scoped>
.visitor-map-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.visitor-map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.header-title {
  text-align: center;
}

.header-title h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 5px;
}

.header-title p {
  color: #606266;
  font-size: 14px;
  margin: 0;
}

.map-wrapper {
  flex: 1;
  position: relative;
  padding: 20px;
}

.map-container {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.status-indicator {
  position: absolute;
  top: 30px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  z-index: 10;
}

.pulse-dot {
  width: 12px;
  height: 12px;
  background-color: #f56c6c;
  border-radius: 50%;
  margin-right: 10px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(0.8);
    opacity: 0.8;
  }
  50% {
    transform: scale(1.2);
    opacity: 1;
  }
  100% {
    transform: scale(0.8);
    opacity: 0.8;
  }
}

.cancel-btn {
  margin-left: 15px;
}

.damage-form {
  padding: 20px;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.upload-item {
  margin-bottom: 20px;
}

.upload-container {
  display: flex;
  align-items: center;
}

.file-input {
  display: none;
}

.upload-button {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 15px;
  background-color: #f2f6fc;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-button:hover {
  border-color: #409eff;
  color: #409eff;
}

.file-name {
  margin-left: 10px;
  color: #606266;
}

.image-preview {
  margin-top: 10px;
  max-width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.image-preview img {
  width: 100%;
  max-height: 200px;
  object-fit: cover;
}
</style>
